package com.cmsky.open.food.controller.admin;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;

import com.cmsky.open.core.util.ErrorMapUtil;
import com.cmsky.open.core.util.JsonUtils;
import com.cmsky.open.core.util.ResourcesUtil;
import com.cmsky.open.food.manager.FoodInfoManager;
import com.cmsky.open.food.model.FoodInfo;
import com.cmsky.open.food.vo.query.FoodInfoQuery;
import com.cmsky.open.shop.model.ShopInfo;
import com.cmsky.open.shop.service.ShopLoginService;

@Controller("admin.food.upload")
@RequestMapping("/admin/food/upload")
public class UploadController {
	protected final static String foodInfoImgPath = "/resources/food/" ;
	private final static Logger logger = Logger.getLogger(UploadController.class);
	
	private FoodInfoManager foodInfoManager;
	private ShopLoginService shopLoginService;
	public void setFoodInfoManager(FoodInfoManager foodInfoManager) {
		this.foodInfoManager = foodInfoManager;
	}
	
	public void setShopLoginService(ShopLoginService shopLoginService) {
		this.shopLoginService = shopLoginService;
	}

	@RequestMapping("/img")
	public ModelAndView foodImg(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("/admin/food/upload/img");
		view.addObject("foodId", request.getParameter("foodId"));
		return view;
	}

	@RequestMapping("/upload")
	@ResponseBody
	public String upload(HttpServletRequest request, HttpServletResponse response) {
		Map<String,Object> result = null;
		String uuid =request.getParameter("uuid");
		MultipartHttpServletRequest  multipartRequest= (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		Integer foodId = Integer.parseInt(request.getParameter("foodId"));
		FoodInfo foodInfo = foodInfoManager.getById(foodId);
		ShopInfo shoper = this.shopLoginService.getLoginedShoper(request, response);;
		if(null==shoper){
			result = ErrorMapUtil.createErrorMap("500", "登录已过期,请重新登录!");
		}else if(shoper.getId() != foodInfo.getShopId() && !this.shopLoginService.isSuper(shoper)){
			result = ErrorMapUtil.createErrorMap("500", "非本商家,不能修改图片!");
		}else{
			String fileName = null;
			for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
				MultipartFile mf = entity.getValue();
				fileName = mf.getOriginalFilename();
				String extendname = fileName.substring(fileName.lastIndexOf(".")).trim();
				if(extendname.equals(".jpg") || extendname.equals(".png") || extendname.equals(".jpeg")){
					String filename = foodId+"desc"+".jpg";
					File uploadFile = new File(ResourcesUtil.getResourseRoot()+foodInfoImgPath+filename);
					try {
						FileCopyUtils.copy(mf.getBytes(), uploadFile);
						if(StringUtils.isBlank(foodInfo.getPic())){
							FoodInfoQuery fiQuery = new FoodInfoQuery();
							fiQuery.setId(foodId);
							fiQuery.setPic(foodInfoImgPath+filename);
							if(this.foodInfoManager.updatePic(fiQuery)<=0){
								result = ErrorMapUtil.createErrorMap("500", "保存数据未成功!");
							}else{
								result = ErrorMapUtil.createErrorMap("0", "上传图片成功!");
							}
						}else{
							result = ErrorMapUtil.createErrorMap("0", "上传图片成功!");
						}
					} catch (IOException e) {
						result = ErrorMapUtil.createErrorMap("500", "内部错误:"+e.getMessage());
						logger.error("<|>upload<|>error<|>"+foodInfo+"<|>"+result+"<|>",e);
					}
				}else{
					result = ErrorMapUtil.createErrorMap("500", "图片格式不对,只支持jpg,png,jpeg!");
				}
			}
		}
		String resultStr = JsonUtils.jsonFromObject(result);
		logger.info("<|>upload<|>"+foodInfo+"<|>"+shoper+"<|>"+resultStr+"<|>");
		return resultStr;
	}
	protected void initBinder(HttpServletRequest request,
	            ServletRequestDataBinder binder) throws ServletException {
	        binder.registerCustomEditor(byte[].class,
	                new ByteArrayMultipartFileEditor());
	}
}
